import React, { Component } from "react";
import { Button, Table, Input, Message } from "antd";
import { connect } from "dva";
import { Link } from "dva/router";
import { ROLE_TYPE_SUPER } from "../constants";
import tableFilter from "../../../../components/tableFilter";
import SelectModalLabel from "./SelectModalLabel";
import LabelColumns from './LabelColumns';
import styles from "./LabelList.less";

const { Search } = Input;

@connect(stores => ({
  user: stores.user,
  stData: stores.labelManager,
  orgData: stores.adddataSource,
}))
@tableFilter
class CustomMade extends Component {
  constructor(props) {
    super(props);
    this.state = {
      status: [],
      searchVal: "",
      rank: "desc",
      pageNum: 1,
      pageSize: 10,
      selectData: [],
      visible: false,
      labelId: -1,
      userLabel: [],
      disableChecked: false, // 新增用户 false、详情查看用户 true
    };
  }

  componentDidMount() {
    this.filterFun();
    this.setDepart();
  }

  setDepart = () => {
    const { dispatch } = this.props;
    dispatch({
      type: "situationList/departData",
      payload: {}
    }).then(() => {
      const { stData } = this.props;
      const { departList = [] } = stData;
      const dep = [];
      departList.forEach(item => {
        dep.push({ text: item.ownerDeptName, value: item.ownerDept });
      });
      this.setState({
        selectData: dep
      });
    });
  };

  handleTableChange = (e, filters, sorter) => {
    const { current, pageSize } = e;
    const { status } = this.state;
    this.setState(
      {
        pageNum:
          filters.status && filters.status !== status
            ? "1"
            : String(current),
        pageSize: String(pageSize),
        rank: sorter.order && sorter.order === "ascend" ? "asc" : "desc",
        status: filters.useStatus ? filters.useStatus : []
      },
      () => {
        this.filterFun();
      }
    );
  };

  filterFun = () => {
    const { searchVal } = this.state;
    this.handleList(searchVal);
  };

  // 查询标签
  onSearch = (value) => {
    this.setState({ searchVal: value });
    this.handleList(value);
  }

  handleList = (value) => {
    const { pageSize, rank, pageNum, status } = this.state;
    const { dispatch, roleType } = this.props;
    dispatch({
      type: "labelManager/getLabelList",
      payload: {
        pageNum,
        pageSize,
        status: status.length ? status[0] : null,
        createTime: rank,
        labelName: value,
        roleType,
      }
    });
  }

  // 更新状态
  handleStatus = (e, labelId, useStatus) => {
    e.preventDefault();
    const { pageSize, pageNum } = this.state;
    const { dispatch, roleType } = this.props;
    dispatch({
      type: "labelManager/updateStatus",
      payload: {
        labelId, 
        useStatus, 
        roleType,
        pageSize,
        pageNum,
      }
    }).then(() => {
      const { stData } = this.props;
      const { departList = [] } = stData;
      const dep = [];
      departList.forEach(item => {
        dep.push({ text: item.ownerDeptName, value: item.ownerDept });
      });
      this.setState({
        selectData: dep
      });
    });
  }

  // 删除标签
  delLabel = (record) => {
    const { pageSize, pageNum } = this.state;
    const { roleType } = this.props;
    const { labelId, useStatus } = record;
    if (useStatus === 1) {
      Message.warning('该标签已启用，无法删除');
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: "labelManager/delLabel",
      payload: {
        labelId,
        roleType,
        pageSize,
        pageNum,
      }
    });
  }

  // 用户详情
  detailUser = (record) => {
    const { labelId, userLabel = [] } = record;
    this.setState({
      visible: true,
      disableChecked: true,
      labelId,
      userLabel,
    });
  }

  // 新增用户
  addUser = (record) => {
    const { labelId, userLabel = [] } = record;
    this.setState({
      visible: true,
      disableChecked: false,
      labelId,
      userLabel,
    });
  }

  onSure = (data) => {
    const { dispatch, roleType } = this.props;
    const { labelId, pageSize, pageNum } = this.state;
    dispatch({
      type: "labelManager/addUser",
      payload: {
        labelId,
        userLabel: data,
        roleType,
        pageSize,
        pageNum,
      }
    });
    this.onCancel();
  }

  onCancel = () => {
    this.setState({ visible: false });
  }

  render() {
    const { stData, roleType } = this.props;
    const { pageNum, visible, userLabel, disableChecked } = this.state;
    const newSel = [];
    const delDuplicate = [];
    this.state.selectData.forEach(item => {
      newSel.push(item.value);
    });
    const temp = [];
    newSel.forEach((item, index) => {
      if (temp.indexOf(item) === -1) {
        temp.push(item);
        delDuplicate.push(this.state.selectData[index]);
      }
    });

    const columns = LabelColumns(
      roleType,
      this.detailUser,
      this.addUser,
      this.delLabel,
      this.handleStatus
    );

    const { STList = [], loading, totalCount } = stData;
    return (
      <div className={styles.root}>
        <div className={styles.header}>
          <Link
            to={ roleType === ROLE_TYPE_SUPER ?
              `/messageCenter/channelManager/labelManager/addLabel`
              :
              `/messageCenter/channelManager/myLabelManager/myAddLabel`
            }
          >
            <Button type="primary" style={{ marginBottom: 16 }}>
              创建标签
            </Button>
          </Link>
          <Search
            placeholder="请输入标签名称检索"
            onSearch={this.onSearch}
            style={{ width: 200, height: 32 }}
          />
        </div>
        <Table
          rowKey={record => record.labelId}
          columns={columns}
          size="middle"
          locale={{ emptyText: "暂无数据！" }}
          dataSource={STList}
          loading={loading}
          onChange={(e, filters, sorter) =>
            this.handleTableChange(e, filters, sorter)
          }
          pagination={{
            defaultPageSize: 10,
            showQuickJumper: true,
            showSizeChanger: true,
            current: pageNum * 1,
            total: totalCount,
            showTotal: total => `共有 ${total} 条`
          }}
        />
        {
          visible ?
            <SelectModalLabel
              onCancel={this.onCancel}
              onSure={this.onSure}
              dataArr={userLabel}
              disableChecked={disableChecked}
              title={disableChecked ? '已启用的标签' : '添加标签用户'}
            />
           : null
        }
      </div>
    );
  }
}

export default CustomMade;
